﻿using System.Net.Sockets;
using System.Windows.Forms;

namespace DasherBci
{
    public class DasherController
    {
        private readonly UdpClient _udpClient = new UdpClient(LocalhostIp, DasherSettings.SocketModePort);
        private const string LocalhostIp = "127.0.0.1";

        public DasherController()
        {
            if (!DasherSettings.DasherRegistryKeyFound)
            {
                throw new DasherBciException(ErrorCode.DasherRegistryKeyNotFound);
            }

            CurrentPosition = VectorOrigin;
        }

        public CoordinatePair CurrentPosition { get; private set; }
        public CoordinatePair VectorOrigin
        {
            get
            {
                return new CoordinatePair(DasherSettings.XCoordinateValueMaximum/2,
                                          DasherSettings.YCoordinateValueMaximum/2);
            }
        }

        public void UpdateVector(CoordinatePair coordinates)
        {
            Send(new CoordinatePairPacket(coordinates));
            CurrentPosition = coordinates;
        }

        private void Send(CoordinatePairPacket packet)
        {
            byte[] packetBytes = packet.GetBytes();
            _udpClient.Send(packetBytes, packetBytes.Length);
        }
    }
}
